package com.example.bgmachine.bgmachine.commons;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;

import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.bgmachine.bgmachine.R;
import com.example.bgmachine.bgmachine.homes.HomePages;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImageloadView extends android.support.v7.widget.AppCompatImageView {
    public static final int GET_DATA_SUCCESS = 1;
    public static final int NETWORK_ERROR = 2;
    public static final int SERVER_ERROR = 3;


    private String mloadimageFiles = "";

    //子线程不能操作UI，通过Handler设置图片
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GET_DATA_SUCCESS:
                    Bitmap bitmap = (Bitmap) msg.obj;
                    if (bitmap != null) {
                        setImageBitmap(bitmap);
                    }

                    break;
                case NETWORK_ERROR:
                    // Toast.makeText(getContext(),"网络连接失败",Toast.LENGTH_SHORT).show();
                    break;
                case SERVER_ERROR:
                    // Toast.makeText(getContext(),"服务器发生错误",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    public ImageloadView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public ImageloadView(Context context) {
        super(context);
    }

    public ImageloadView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void saveToSystemGallery(Bitmap bmp, String fileNames) {
        // 首先保存图片
        File pathsFile = HomePages.mHomePages.getBaseContext().getDir("users", Context.MODE_PRIVATE);//Environment.getExternalStorageDirectory();//getDataDirectory();// mContext.getDir("users", Context.MODE_PRIVATE);

        File appDir = new File(pathsFile, "temp");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = fileNames;
        Log.d("aaa", "saveToSystemGallery: mfilePathname=1=" + fileName);
        File file = new File(appDir, fileName);

        String mfilePathname = file.getAbsolutePath();
        Log.d("aaa", "saveToSystemGallery: mfilePathname=1=" + mfilePathname);
        try {
            Log.d("aaa", "saveToSystemGallery=0");
            FileOutputStream fos = new FileOutputStream(file);
            Log.d("aaa", "saveToSystemGallery=01");
            if (mfilePathname.contains(".png")) {
                Log.d("aaa", "saveToSystemGallery=02");
                bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
                Log.d("aaa", "saveToSystemGallery=03");
            }
            Log.d("aaa", "saveToSystemGallery=1");
            if (mfilePathname.contains(".jp")) {
                Log.d("aaa", "saveToSystemGallery=04");
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                Log.d("aaa", "saveToSystemGallery=05");
            }
            Log.d("aaa", "saveToSystemGallery=2");
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Log.d("aaa", "saveToSystemGallery=3");
    }

    public boolean fileIsExists(String fileName) {
        try {
            // 首先保存图片
            File pathsFile = HomePages.mHomePages.getBaseContext().getDir("users", Context.MODE_PRIVATE);//Environment.getExternalStorageDirectory();//getDataDirectory();// mContext.getDir("users", Context.MODE_PRIVATE);

            File appDir = new File(pathsFile, "temp");
            if (!appDir.exists()) {
                Log.d("aaa", "fileIsExists==1");
                appDir.mkdir();
            } else {
                Log.d("aaa", "fileIsExists==2");
            }

            File f = new File(appDir, fileName);

            if (f.exists()) {

                return true;
            } else {

                return false;
            }
        } catch (Exception e) {
            Log.i("aaa", "崩溃");
            return false;
        }
    }

    //设置网络图片
    public void setImageURL(final String path, String imageFiles) {
        Log.d("aaa", "setImageURL:path==" + path);
        Log.d("aaa", "setImageURL:imageFiles==" + imageFiles);
        /*
        this.setImageResource(R.mipmap.homepage_grid__item_image_demos);
        if (true) {
            return;
        }
        */

        if (fileIsExists(imageFiles)) {
            String pathsb = HomePages.mHomePages.mSourcePaths + "/" + imageFiles;
            Log.d("aaa", "getView: pathsb=1=" + pathsb);
            Bitmap bitmapb = HomePages.mHomePages.mloadImage.get(imageFiles);
            Bitmap bitmap =null;
            if(bitmapb == null){
                bitmap =BitmapFactory.decodeFile(pathsb);
                HomePages.mHomePages.mloadImage.put(imageFiles,bitmap);
            }else{
                bitmap =bitmapb;
            }

            if (bitmap != null) {
                Log.d("aaa", "getView: pathsb=10=" + pathsb);
//                Message msg = Message.obtain();
//                msg.obj = bitmap;
//                msg.what = GET_DATA_SUCCESS;
//                handler.sendMessage(msg);
                if (bitmap != null) {
                    setImageBitmap(bitmap);
                }

            } else {
                this.setImageResource(R.mipmap.homepage_grid__item_image_demos);

            }

            return;
        }
        mloadimageFiles = imageFiles;
        //开启一个线程用于联网
        new Thread() {
            @Override
            public void run() {
                try {
                    String imageFilea = mloadimageFiles;
                    //把传过来的路径转成URL
                    URL url = new URL(path);
                    //获取连接
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    //使用GET方法访问网络
                    connection.setRequestMethod("GET");
                    //超时时间为10秒
                    connection.setConnectTimeout(10000);
                    //获取返回码
                    int code = connection.getResponseCode();
                    if (code == 200) {
                        InputStream inputStream = connection.getInputStream();
                        //使用工厂把网络的输入流生产Bitmap
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        saveToSystemGallery(bitmap,imageFilea);
                        //利用Message把图片发给Handler
//                        Message msg = Message.obtain();
//                        msg.obj = bitmap;
//                        msg.what = GET_DATA_SUCCESS;
//                        handler.sendMessage(msg);
//                        inputStream.close();
                    } else {
                        //服务启发生错误
                        handler.sendEmptyMessage(SERVER_ERROR);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    //网络连接错误
                    handler.sendEmptyMessage(NETWORK_ERROR);
                }
            }
        }.start();
    }

}
